package com.itheima.sh.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.sh.pojo.User;
import com.itheima.sh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping
    public User add( @RequestBody User user) {
        userService.save(user);   // 保存成功， 主键会自动封装到 User的主键属性上
        return user;
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable("id") Long id) {
        return userService.removeById(id);
    }

    @PutMapping("/{id}")
    public boolean update(@PathVariable("id") Long id,@RequestBody User user) {
        return userService.update(user, Wrappers.<User>lambdaQuery().eq(User::getId, id));
    }


    @GetMapping("/{id}")
    public User findOne(@PathVariable("id") Long id) {
        return userService.getById(id);
    }


    @PostMapping("findList")
    public List<User> findList(@RequestBody User user) {

        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();

        if (user.getUserName()!=null && user.getUserName().length() > 0) {
            wrapper.like(User::getUserName, user.getUserName());
        }

        if (user.getAge() != null) {
            wrapper.eq(User::getAge, user.getAge());
        }

        List<User> list = userService.list(wrapper);
        return list;
    }


    @PostMapping("findPage/{page}/{size}")
    public Page<User> findPage(@PathVariable("page") Long current, @PathVariable("size") Long size,
                               @RequestBody User user) {

        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();

        if (user.getUserName()!=null && user.getUserName().length() > 0) {
            wrapper.like(User::getUserName, user.getUserName());
        }

        if (user.getAge() != null) {
            wrapper.eq(User::getAge, user.getAge());
        }
        Page<User> page = new Page<>(current,size);
        return userService.page(page,wrapper);
    }

}
